const currentUTC:Date = new Date();
class Jsonp {
  url:string;
  callback:string;
  constructor() {

  }

  /**
   * 发送jsonp请求
   * @param {string} url
   * @param {string} callbackName
   * @param {object} params 要传递给callback的参数
   */
  static send(url:string, callbackName:string, params:object){
    Jsonp.appendScript(Jsonp.generateUrl(url, callbackName, params));
  }

  /**
   * @param {string} url
   */
  static appendScript(url:string){
    document.getElementsByTagName('head')[0].appendChild(Jsonp.createScript(url));
  }

  /**
   * 构造适用于jsonp的url
   * Jsonp.getUTC用于避免缓存
   * @param {string} url
   * @param {string} callbackName
   * @param {object} params 要传递给API接口的参数
   * @return {string} result
   */
  static generateUrl(url:string, callbackName:string, params:object){
    return encodeURI(url+'?callback='+callbackName+String(Jsonp.getUTC())+Jsonp.generateParam(params));
  }

  /**
   * @param {string} url
   * @return {HTMLElement} result
   */
  static createScript(url:string){
    let script = document.createElement('script');
    script.setAttribute('src', url);
    return script;
  }

  /**
   * @param {object} params
   * @return {string} result
   */
  static generateParam(params:object){
    const keys = Object.keys(params);
    if(keys.length===0)return '';
    let param = '';
    keys.map((key,index)=>{
      if(index===1){
        param += '?';
      }
      if(index===(keys.length-1)){
        return param += key+'='+JSON.stringify(params[key]);
      }
      param += key+'='+String(params[key])+'&';
    });
  }


  /**
   * 返回当前UTC时间
   * @return {number} result
   */
  static getUTC(){
    return Date.UTC(
      currentUTC.getFullYear(),
      currentUTC.getMonth()+1,
      currentUTC.getDate(),
      currentUTC.getMinutes(),
      currentUTC.getSeconds(),
      currentUTC.getMilliseconds())
  }
}
